//
//  RecommendController.m
//  Kugou-OC
//
//  Created by BH on 16/5/27.
//  Copyright © 2016年 Sunny. All rights reserved.
//

#import "RecommendController.h"
#import "ScrollviewBanner.h"
#import "NetworkHelper.h"
#import "GlobalDefine.h"
#import "CLRefreshHeader.h"
#import "RecommendCell.h"
#import "RecommendModel.h"
#import "TapImageView.h"
#import <MJRefresh/UIScrollView+MJRefresh.h>
#import <SDAutoLayout/UIView+SDAutoLayout.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface RecommendHeaderView : UIView{
    NSMutableArray *btnImgArray;
    ScrollviewBanner *bannerView;
}

@property(nonatomic,strong)NSArray *bannerBtnArray;
@property(nonatomic,strong)NSArray *bannerImgArray;

@end

@implementation RecommendHeaderView

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    
    return self;
}

-(void)setBannerBtnArray:(NSArray *)bannerBtnArray{
    _bannerBtnArray = bannerBtnArray;

    TapImageView *btnImg = nil;
    UILabel *btnLab = nil;
    for (int i=0; i<bannerBtnArray.count; i++) {
        TapImageView *imageV = ALLOC(TapImageView);
        imageV.tag = 200+i;
        [imageV sd_setImageWithURL:[NSURL URLWithString:[[bannerBtnArray[i] ent_model] imgUrl]] placeholderImage:nil];
        
        UILabel *label = ALLOC(UILabel);
        label.font = TITLE_FOUR_FONT;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = [[bannerBtnArray[i] ent_model] title];
        [self sd_addSubviews:@[imageV,label]];
        
        if (btnImg) {
            imageV.sd_layout.leftSpaceToView(btnImg,40).topSpaceToView(bannerView,10).widthIs((SCREEN_WIDTH-40*bannerBtnArray.count)/4).heightEqualToWidth();
            label.sd_layout.leftSpaceToView(btnLab,0).topSpaceToView(imageV,10).widthIs(SCREEN_WIDTH/bannerBtnArray.count).heightIs(25);
        }else{
            imageV.sd_layout.leftSpaceToView(self,20).topSpaceToView(bannerView,10).widthIs((SCREEN_WIDTH-40*bannerBtnArray.count)/4).heightEqualToWidth();
            label.sd_layout.leftEqualToView(self).topSpaceToView(imageV,10).widthIs(SCREEN_WIDTH/4).heightIs(25);
        }
        
        btnImg = (TapImageView*)imageV;
        btnLab = label;
        
        btnImg.Taphandle = ^(UIImageView *view){
            NSLog(@"%@",[[bannerBtnArray[view.tag-200] ent_model] title]);
        };
    }
}

-(void)setBannerImgArray:(NSArray *)bannerImgArray{
    _bannerImgArray = bannerImgArray;
    
    bannerView = [[ScrollviewBanner alloc] init];
    bannerView.itemsSource = KBannerSourceTypeNetwork;
    bannerView.items = _bannerImgArray;
    [self addSubview:bannerView];
    bannerView.sd_layout.leftSpaceToView(self,0).rightSpaceToView(self,0).topSpaceToView(self,0).heightIs(150);
}

@end

/*----------------------------------------------------------------------------------------------------*/
@interface RecommendController ()<UITableViewDataSource,UITableViewDelegate>{

    RecommendHeaderView *headerView;
}

@property(nonatomic,strong)UITableView *table;
@property(nonatomic,strong)NSMutableArray *bannerArray;//ads数组
@property(nonatomic,strong)NSMutableArray *bannerImgArray;//ads图片
@property(nonatomic,strong)NSMutableArray *personal;//个性化
@property(nonatomic,strong)NSMutableArray *recommend;//热门歌单 recommend
@property(nonatomic,strong)NSMutableArray *operation;//operation
@property(nonatomic,strong)NSMutableArray *song;//最新音乐-新歌首发 song
@property(nonatomic,strong)NSMutableArray *album;//最新音乐-新碟上架 album
@property(nonatomic,strong)NSMutableArray *vlist;//MV歌单 vlist
@property(nonatomic,strong)NSMutableArray *customspecial;//custom_special (场景歌单、主题歌单)
@property(nonatomic,strong)NSMutableArray *entry;//header按钮 entry
@property(nonatomic,strong)NSMutableArray *topic;//精选专题 topic
@property(nonatomic,strong)NSArray *sectionTitle;//节头数组

@end

@implementation RecommendController

- (void)viewDidLoad {
    [super viewDidLoad];

    //获取其他信息
    [self getMoreInfo];
    //获取个性化推荐
    [self getPersonalRecommend];
}

#pragma mark - 懒加载
-(UITableView *)table{
    if (_table == nil) {
        _table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-90-64-30) style:UITableViewStylePlain];
        _table.dataSource = self;
        _table.delegate = self;
        
        headerView = [[RecommendHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150+(SCREEN_WIDTH-40*self.entry.count)/4+25+25)];
        headerView.bannerImgArray = _bannerImgArray;
        headerView.bannerBtnArray = self.entry;
        _table.tableHeaderView = headerView;
        
//        _table.mj_header = [CLRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    }
    
    return _table;
}

-(NSArray *)sectionTitle{
    if (_sectionTitle == nil) {
        _sectionTitle = [NSArray arrayWithObjects:@"个性化推荐",@"最新音乐",@"热门歌单",@"主题歌单",@"MV歌单",@"精选专题",nil];
    }
    
    return _sectionTitle;
}

-(NSMutableArray *)recommend{
    if (_recommend == nil) {
        _recommend = ALLOC(NSMutableArray);
    }
    
    return _recommend;
}

-(NSMutableArray *)entry{
    if (_entry == nil) {
        _entry = ALLOC(NSMutableArray);
    }
    
    return _entry;
}

-(NSMutableArray *)song{
    if (_song == nil) {
        _song = ALLOC(NSMutableArray);
    }
    
    return _song;
}

-(NSMutableArray *)album{
    if (_album == nil) {
        _album = ALLOC(NSMutableArray);
    }
    
    return _album;
}

-(NSMutableArray *)customspecial{
    if (_customspecial == nil) {
        _customspecial = ALLOC(NSMutableArray);
    }
    
    return _customspecial;
}

-(NSMutableArray *)vlist{
    if (_vlist == nil) {
        _vlist = ALLOC(NSMutableArray);
    }
    
    return _vlist;
}

-(NSMutableArray *)topic{
    if (_topic == nil) {
        _topic = ALLOC(NSMutableArray);
    }
    
    return _topic;
}

/**
 *  获取banner信息
 */
-(void)getAdsData{
    NSString *urlstr = @"http://ads.service.kugou.com/v1/mobile_fmbanner?plat=2&version=8100&operator=1&networktype=1&phonebrand=iPhone&ismonthly=0&isvip=0&mid=8b3ca0559064ff39e68150c55e7b752746f20d1d&userid=0&appid=1000&clientver=8100&clienttime=1466041815&key=036baeb2acd2a4af1fecf1484ac211f4&type=4";
    
    [[NetworkHelper shareNetwork] getDataWithUrl:urlstr view:self.view success:^(id response) {
        NSArray *infoArr = response[@"data"][@"info"];
        
        _bannerImgArray = [NSMutableArray array];
        _bannerArray = [NSMutableArray array];
        
        for (NSDictionary *info in infoArr) {
            RecommendModel *model = [[RecommendModel shareRecommend] initWithAdsDict:info];
            [_bannerImgArray addObject:model.ad_model.imgUrl];
            [_bannerArray addObject:model];
        }
        
        [self.view addSubview:self.table];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

-(void)getPersonalRecommend{
    NSString *url = @"http://service.mobile.kugou.com/v1/yueku/multi_special_recommend";
    NSDictionary *param = @{@"hash":@"40c5f4376d38543c2f4ef1f7dcd9ddba,896f8635211f17e9100461bd63486105,b4d06375911676876e97b5265777055c,35041338513f0f8af1e8e6360ff6fe4e,73fab88f6cf8d80e4336dfdfc1e19824,0a87ac46af8b81bf443cbf81586b7a41,93d1b7a85bc6ed14914521ccb95e46cc,cd653e9353a8ce7cd93a0d8167c0cc0b,5e4207041e05e0ee347903295efc1d95,9283c8fea2871e449328bcd49d283471,fde901dff6c31762e140e50d9291ec33,4d15e97116327e9f16f897d957b81d9e,08f7cb00b1cdf7b8a65d2d5e4f8190d6,f5c478f4215bc4397a3747b36a15a9d4,f2c51497756632ef7d24618b10c61e9a",@"type":@"2"};
    
    _personal = ALLOC(NSMutableArray);
    
    [[NetworkHelper shareNetwork] getDataWithUrl:url params:param view:self.view success:^(id response) {
        NSArray *infoArr = response[@"data"][@"info"];
        for (NSDictionary *dict in infoArr) {
            RecommendModel *model = [[RecommendModel alloc] initWithPersonalDict:dict];
            [_personal addObject:model];
        }
    } failure:^(NSError *error) {
        
    }];
    
}

-(void)getMoreInfo{
    
    NSString *url = @"http://service.mobile.kugou.com/v1/yueku/recommend";
    NSDictionary *params = @{@"type":@"6",@"plat":@"2",@"version":@"8100",@"operator":@"1"};
    
    [[NetworkHelper shareNetwork] getDataWithUrl:url params:params view:self.view success:^(id response) {
        
        NSArray *entryTemp = response[@"data"][@"info"][@"entry"];
        
        for (NSDictionary *dict in entryTemp) {
            RecommendModel *model = [[RecommendModel alloc] initWithEntryDict:dict];
            
            [self.entry addObject:model];
        }
        
        NSArray *recommend = response[@"data"][@"info"][@"recommend"];
        for (NSDictionary *dict in recommend) {
            RecommendModel *model = [[RecommendModel alloc] initWithRecDict:dict];
            [self.recommend addObject:model];
        }
        
        NSArray *song = response[@"data"][@"info"][@"song"];
        for (NSDictionary *dict in song) {
            RecommendModel *model = [[RecommendModel alloc] initWithSongDict:dict];
            [self.song addObject:model];
        }
        
        NSArray *album = response[@"data"][@"info"][@"album"];
        for (NSDictionary *dict in album) {
            RecommendModel *model = [[RecommendModel alloc] initWithAlbumDict:dict];
            [self.album addObject:model];
        }
        
        NSArray *custom = response[@"data"][@"info"][@"custom_special"];
        for (NSDictionary *dict in custom) {
            RecommendModel *model = [[RecommendModel alloc] initWithCusDict:dict];
            [self.customspecial addObject:model];
        }
        
        NSArray *vlist = response[@"data"][@"info"][@"vlist"];
        for (NSDictionary *dict in vlist) {
            RecommendModel *model = [[RecommendModel alloc] initWithVlistDict:dict];
            [self.vlist addObject:model];
        }
        
        NSArray *topic = response[@"data"][@"info"][@"topic"];
        for (NSDictionary *dict in topic) {
            RecommendModel *model = [[RecommendModel alloc] initWithTopicDict:dict];
            [self.topic addObject:model];
        }
        
        [self getAdsData];
        
    } failure:^(NSError *error) {
        
    }];
}

-(void)loadData{
    
}

#pragma mark - UITableview datasource & delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionTitle.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        return 4;
    }else if (section == 3){
        return 1;
    }else if (section == 5){
        return self.topic.count;
    }
    
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RecommendCell *cell = [RecommendCell cellWithTableView:tableView];
    cell.indexpath = indexPath;
    
    if (indexPath.section == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.celltype = kRecommendCellTypeStandard;
        cell.recommendM = self.personal[indexPath.row];
    }else if (indexPath.section == 1){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.celltype = kRecommendCellTypeMoreSubtitle;
        if (indexPath.row == 0) {
            cell.recommendArray = self.song;
        }else{
            cell.recommendArray = self.album;
        }
    }else if(indexPath.section == 2){
        
        if (indexPath.row == 0) {
            cell.recommendArray = [NSArray arrayWithObjects:self.recommend[0],self.recommend[1],self.recommend[2],nil];
        }else{
            cell.recommendArray = [NSArray arrayWithObjects:self.recommend[3],self.recommend[4],self.recommend[5],nil];
        }
        cell.celltype = kRecommendCellTypeCollectItems;
    }else if (indexPath.section == 3){
        cell.recommendArray = self.customspecial;
        cell.celltype = kRecommendCellTypeCollectItems;
    }else if (indexPath.section == 4){
        if (indexPath.row == 0) {
            cell.recommendArray = [NSArray arrayWithObjects:self.vlist[0],self.vlist[1],nil];
        }else{
            cell.recommendArray = [NSMutableArray arrayWithObjects:self.vlist[2],self.vlist[3],nil];
        }
        
        cell.celltype = kRecommendCellTypeCollectItems;
    }else{
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.celltype = kRecommendCellTypeStandard;
        cell.recommendM = self.topic[indexPath.row];
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return 90;
    }else if (indexPath.section == 1){
        return 100;
    }else if (indexPath.section == 5){
        return 70;
    }
    return (SCREEN_WIDTH-80)/3+40+15;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = ALLOC(UIView);
    sectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    sectionView.backgroundColor = [UIColor whiteColor];
    
    UILabel *sectionLab = ALLOC(UILabel);
    sectionLab.font = TITLE_THIRD_FONT;
    sectionLab.textColor = BG_COLOR;
    sectionLab.text = self.sectionTitle[section];
    [sectionView addSubview:sectionLab];
    
    UIButton *sectionBtn = ALLOC(UIButton);
    sectionBtn.titleLabel.font = TITLE_FIVE_FONT;
    [sectionBtn setTitleColor:BG_COLOR forState:UIControlStateNormal];
    [sectionBtn setTitle:@"更多>" forState:UIControlStateNormal];
    [sectionView addSubview:sectionBtn];
    
    if (section == 1 || section == 3) {
        sectionBtn.hidden = YES;
    }
    
    sectionBtn.sd_layout.rightSpaceToView(sectionView,0).centerYEqualToView(sectionView).heightIs(sectionView.height).widthIs(90);
    sectionLab.sd_layout.leftSpaceToView(sectionView,15).rightSpaceToView(sectionBtn,5).topEqualToView(sectionView).bottomEqualToView(sectionView);
    
    return sectionView;
}

/**
 *  重载scrollview的delegate方法，取消section header悬停
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

@end
